<?php

// application/models/TbladresseMapper.php
class Application_Model_TbladresseMapper {

    protected $_dbTable;
    private $logger;

    public function setDbTable($dbTable) {
        if (is_string($dbTable)) {
            $dbTable = new $dbTable();
        }
        if (!$dbTable instanceof Zend_Db_Table_Abstract) {
            throw new Exception('Invalid table data gateway provided');
        }
        $this->_dbTable = $dbTable;
        return $this;
    }

    public function getDbTable() {
        if (null === $this->_dbTable) {
            $this->setDbTable('Application_Model_DbTable_Tbladresse');
        }
        return $this->_dbTable;
    }

    public function save(Application_Model_Tbladresse $tbladresse) {
        $this->logger = Zend_Registry::get('logger');
        $this->logger->info("Hello from Application_Model_TbladresseMapper **" . $tbladresse->getCode_postal() . "***");
        
        $data = array(
            'id' => $tbladresse->getId(),
            'company_id' => $tbladresse->getCompany_id(),
            'adresse' => $tbladresse->getAdresse(),
            'code_postal' => $tbladresse->getCode_postal(),
            'ville' => $tbladresse->getVille(),
            'pays' => $tbladresse->getPays(),
            'last_updated_on' => date('Y-m-d H:i:s')
        );

        $this->logger->info(Zend_Debug::dump($data, $label = null, $echo = true));

        if (null === ($id = $tbladresse->getId())) {
            unset($data['id']);
            $this->getDbTable()->insert($data);
        } else {
            $this->getDbTable()->update($data, array('id = ?' => $id));
        }
    }

    public function find($id, Application_Model_Tbladresse $tbladresse) {
        $result = $this->getDbTable()->find($id);
        if (0 == count($result)) {
            return;
        }
        $row = $result->current();
        $tbladresse->setId($row->id)
                ->setCompany_id($row->company_id)
                ->setAdresse($row->adresse)
                ->setCode_postal($row->code_postal)
                ->setVille($row->ville)
                ->setPays($row->pays)
                ->setLast_updated_on($row->last_updated_on)
        ;
    }

    public function fetchAll() {
        $resultSet = $this->getDbTable()->fetchAll();
        $entries = array();
        foreach ($resultSet as $row) {
            $entry = new Application_Model_Tbladresse();
            $entry->setId($row->id)
                    ->setCompany_id($row->company_id)
                    ->setAdresse($row->adresse)
                    ->setCode_postal($row->code_postal)
                    ->setVille($row->ville)
                    ->setPays($row->pays)
                    ->setLast_updated_on($row->last_updated_on)
            ;
            $entries[] = $entry;
        }
        return $entries;
    }

}
